# coding=utf=8
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.http.response import JsonResponse, HttpResponse
from sms_intercept_backend.models import ReportedSms, Blacklist


def ext_api(func):
    def __func(request, *args, **kwargs):

        try:
            response = func(request, *args, **kwargs)
            if isinstance(response, HttpResponse):
                return response

            if 'success' not in response:
                response['success'] = True
            return JsonResponse(response)
        except Exception as e:
            msg = u'未知错误'
            print e
            return JsonResponse(dict(success=False, msg=msg))

    return __func


class ReportForm(forms.Form):
    body = forms.CharField()
    address = forms.CharField()
    device = forms.CharField()


@ext_api
def report(request):
    form = ReportForm(request.GET)
    if not form.is_valid():
        return {'success': False, 'errors': form.errors.keys()}

    # 插入数据库
    sms = ReportedSms()
    sms.body = form.cleaned_data['body']
    sms.address = form.cleaned_data['address']
    sms.device = form.cleaned_data['device']
    sms.save()
    try:
        blacklist = Blacklist.objects.get(address=sms.address)
    except ObjectDoesNotExist:
        blacklist = Blacklist()
        blacklist.address = sms.address
        blacklist.freq = 0
    blacklist.freq += 1
    blacklist.save()

    return {}


class BlacklistForm(forms.Form):
    count = forms.IntegerField()
    device = forms.CharField()


@ext_api
def blacklist(request):
    form = BlacklistForm(request.GET)
    if not form.is_valid():
        return {'success': False, 'errors': form.errors.keys()}

    list = Blacklist.objects.order_by('-freq')[:form.cleaned_data['count']]
    return {'list': [i.address for i in list]}
